package com.itlong.cloud.controller.sdkV1.old.serverClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.sdk.SDKAuthRelationsGetPageVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerAppUserSaveVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.AppUserRoomHouserTypeEnum;
import com.itlong.cloud.enumerate.PropertyPublicRoleEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.project.sdk.ISDKServerOldProjectServiceClient;
import com.itlong.cloud.project.sdk.ISDKServerOldRoomServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppOldMineServiceClient;
import com.itlong.cloud.user.sdk.ISDKAppOldUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.RandomUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <desc>
 *      SDK服务端用户信息Controller
 * </desc>
 *
 * @createDate 2017/10/26
 */
@RestController
@RequestMapping("/jiabanjing/interface")
public class SDKServerOldUserController {


    private static final Logger LOG = LoggerFactory.getLogger(SDKServerOldUserController.class);

    @Autowired
    ISDKServerOldUserServiceClient iSDKUserServiceClient;

    @Autowired
    ISDKServerOldRoomServiceClient  iSDKServerRoomClient;

    @Autowired
    ISDKServerOldProjectServiceClient iSDKServerOldProjectServiceClient;

    @Autowired
    IAppOldMineServiceClient iAppOldMineServiceClient;

    @Autowired
    ISDKAppOldUserServiceClient isdkAppOldUserServiceClient; //旧版APP_SDK用户服务暴露层接口

    

   /**
    * <desc>
    *       授权业主，非增量添加：每次都要把业主的全部房间带上,以达到更新的目的
    *       如果原来业主下有授权的住户，则将原业主的授权住户的关系挂到新业主下
    * <desc/>
    * @param    appid   应用接入凭证
    * @param    userPhone   授权手机号
    * @param    projectId   项目编号
    * @param    roomJson   授权地址信息
    * @return   Message   老版标准格式化响应结果
    * @author Biao.R
    * @createDate 2017/11/16
    */
    @ResponseBody
    @RequestMapping("/server/authHouser/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_HOUSEOWNER_LOG_DESC)
    public Message addHouser(String appid, String userPhone, String projectId, String roomJson) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            if (StringUtils.isEmpty(userPhone) || !userPhone.matches(PlatformConstants.USER_PHONENUM_REGIX)) {
                return new Message(Code.PARAM_ERR, "userPhone号为空或格式不正确：" + userPhone);
            }
            if (StringUtils.isEmpty(roomJson)) {
                return new Message(Code.PARAM_ERR, "授权地址不能为空");
            }

            JSONArray errorArr = new JSONArray();
            JSONObject js = new JSONObject();
            JSONObject roomObject = JSONObject.parseObject(roomJson);
            JSONArray roomArr = JSON.parseArray(roomObject.getString("roomArr"));
            //根据roomArr查询房间数据
            List<SDKRoomInfoSaveDTO> userRoomList = new ArrayList<>();
            for (int i = 0; i < roomArr.size(); i++) {
                JSONObject room = roomArr.getJSONObject(i);
                String buildNum = room.getString("buildNum");
                String unitNum = room.getString("unitNum");
                String roomNum = room.getString("roomNum");
                if (!(buildNum.matches("\\d{3}") && unitNum.matches("\\d{2}") && roomNum.matches("\\d{4}"))) {
                    errorArr.add(JSONObject.toJSON("楼栋编号必须为3位,单元编号必须为2位,房间编号必须为4位:buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum));
                }
                Map<String, Object> params = new HashMap<>();
                params.put("projectId", desProjectId);
                params.put("buildNum", buildNum);
                params.put("unitNum", unitNum);
                params.put("roomNum", roomNum);
                List<RoomInfoPO> returnRoomList = iSDKServerRoomClient.getRoomByPiBnUnRn(params);
                if (returnRoomList != null && !returnRoomList.isEmpty()) {

                    SDKRoomInfoSaveDTO sdkRoomInfoSaveDTO = new SDKRoomInfoSaveDTO();
                    BeanUtils.copyProperties(returnRoomList.get(0),sdkRoomInfoSaveDTO);
                    userRoomList.add(sdkRoomInfoSaveDTO);
                } else {
                    //所添加的房间不存在
                    errorArr.add(JSONObject.toJSON("请检查房间地址是否存在:buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum));
                }
            }
            if (userRoomList == null || userRoomList.isEmpty()) {
                return new Message(Code.NOT_PARAM, String.format("%s:%s", "请检查roomJson中的房间是否存在", roomJson));
            }
            if (errorArr.size() > 0) {
                js.put("errorArr", errorArr);
                return new Message(Code.PARAM_ERR, js);
            }
            SDKSaveAppUserDTO sdkSaveAppUserDTO = new SDKSaveAppUserDTO(desProjectId, appid, userPhone,
                    AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType(), userRoomList, null);
            SDKServerAppUserSaveVO saveVO = iSDKUserServiceClient.addHouserOrFamily(sdkSaveAppUserDTO);
            if (saveVO != null) {
                List<Map<String, Object>> roomList = saveVO.getRoomList();
                for (Map<String, Object> roomMap : roomList) {
                    String roomId = (String) roomMap.get("roomId");
                    for (SDKRoomInfoSaveDTO sdkRoomInfoSaveDTO : userRoomList) {
                        if (roomId.equals(sdkRoomInfoSaveDTO.getRoomId())) {
                            roomMap.put("buildNum", sdkRoomInfoSaveDTO.getBuildNum());
                            roomMap.put("unitNum", sdkRoomInfoSaveDTO.getUnitNum());
                            roomMap.put("roomNum", sdkRoomInfoSaveDTO.getRoomNum());
                        }
                    }
                }
                js.put("roomInfos", "本次共给 " + userPhone + " 用户添加：" + saveVO.getRoomList().size() + "个房间的业主权限");
            }
            return new Message(Code.SUCCESS, js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_addHouser】授权业主异常", e);
        }
    }



    /**
     * <desc>
     *      业主授权家人
     * <desc/>
     * @param       sdkUserFamilySaveDTO  添加家人数据对象
     * @return      Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/21
     */
    @ResponseBody
    @RequestMapping("/app/authPerson/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_FAMILY_LOG_DESC)
    public Message authPerson(SDKUserFamilySaveDTO sdkUserFamilySaveDTO){
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(sdkUserFamilySaveDTO.getProjectId());
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            String appid = sdkUserFamilySaveDTO.getAppid();
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            String userPhone = sdkUserFamilySaveDTO.getUserPhone();
            String authPhoneNo = sdkUserFamilySaveDTO.getAuthPhoneNo();
            if(StringUtils.isEmpty(userPhone) || !userPhone.matches( PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "userPhone为空或格式不正确：" + userPhone);
            }

            if(StringUtils.isEmpty(authPhoneNo) || !authPhoneNo.matches(PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "authPhoneNo为空或格式不正确：" + authPhoneNo);
            }

            if(userPhone.equals(authPhoneNo)){
                return new Message(Code.PARAM_ERR,"授权账号和被授权账号不能相同");
            }
            String buildNum = sdkUserFamilySaveDTO.getBuildNum();
            String unitNum = sdkUserFamilySaveDTO.getUnitNum();
            String roomNum = sdkUserFamilySaveDTO.getRoomNum();
            if(!(buildNum.matches("\\d{3}") && unitNum.matches("\\d{2}") && roomNum.matches("\\d{4}"))){
                return new Message(Code.PARAM_ERR,String.format("%s:buildNum:%s,unitNum:%s,roomNum:%s","授权地址格式异常",buildNum,unitNum,roomNum));
            }

            //查询被授权地址是否存在
            Map<String, Object> params = new HashMap<>();
            params.put("projectId", desProjectId);
            params.put("buildNum", buildNum);
            params.put("unitNum", unitNum);
            params.put("roomNum", roomNum);
            List<RoomInfoPO> returnRoomList = iSDKServerRoomClient.getRoomByPiBnUnRn(params);
            if(returnRoomList ==null || returnRoomList.isEmpty()){
                return  new Message(Code.PARAM_ERR,"请检查房间地址是否存在");
            }
            List<SDKRoomInfoSaveDTO> userRooms = new ArrayList<>();
            for (RoomInfoPO roomInfoPO : returnRoomList) {
                SDKRoomInfoSaveDTO sdkRoomInfoSaveDTO = new SDKRoomInfoSaveDTO();
                BeanUtils.copyProperties(roomInfoPO,sdkRoomInfoSaveDTO);
                userRooms.add(sdkRoomInfoSaveDTO);
            }

            String roomId = returnRoomList.get(0).getRoomId();
            //检查userPhone是否是该房间的业主
            Map<String,Object> param = new HashMap<>();
            param.put("roomId",roomId);
           /* //检查被授权人是否已经在该房间
            param.put("phoneNum",authPhoneNo);
            List<AppUserRoomPO> userRoomList = iSDKUserServiceClient.getUserRoomByParam(param);
            if(userRoomList !=null && !userRoomList.isEmpty()){
                return new Message(Code.ERROR, "该住户在该房间已经被授权过！");
            }*/

            param.put("phoneNum",userPhone);
            param.put("houserType", AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_OWNER.getType());
            List<AppUserRoomPO> userRoomList = iSDKUserServiceClient.getUserRoomByParam(param);
            if(userRoomList ==null || userRoomList.isEmpty()){
                return  new Message(Code.PARAM_ERR,"userPhone账号在该房间没有戶主权限");
            }
            String parentUserId = userRoomList.get(0).getUserId();

            //检查该房间的最大授权数是否超过限制
            ProjectPO projectPO = iSDKServerOldProjectServiceClient.getByProjectId(desProjectId);
            Integer authMaxNum = projectPO.getAuthMaxNum();
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("parentUserId",parentUserId);
            paramMap.put("roomId",roomId);
            List<AppAuthRelationsPO>  authRelationsPOs =iSDKUserServiceClient.getAuthRelationsByParams(paramMap);
            Integer authRelationCount = (authRelationsPOs ==null || authRelationsPOs.isEmpty())?0:authRelationsPOs.size();

            authMaxNum = (authMaxNum == null) ? 10 : authMaxNum;
            if (authRelationCount >= authMaxNum) {
                return new Message(Code.ERROR, "该房间的人数超过该小区的最大授权数，请联系物业！");
            }

            SDKSaveAppUserDTO sdkSaveAppUserDTO = new SDKSaveAppUserDTO(desProjectId,parentUserId, authPhoneNo,
                    AppUserRoomHouserTypeEnum.USERROOM_HOUSERTYPE_RELATIVES.getType(), userRooms,sdkUserFamilySaveDTO.getUserRemarks());
            SDKServerAppUserSaveVO saveVO = iSDKUserServiceClient.addHouserOrFamily(sdkSaveAppUserDTO);
            JSONObject js = new JSONObject();
            AppUserInfoPO userInfoPO = iSDKUserServiceClient.getAppUserByPhone(authPhoneNo);
            js.put("userPhone", authPhoneNo);
            js.put("projectName", projectPO.getProjectName());
            js.put("userRemarks", sdkUserFamilySaveDTO.getUserRemarks());
            js.put("userName",userInfoPO.getRealName());
            js.put("photoUrl", userInfoPO.getIcon());
            js.put("createTime", userInfoPO.getCreateTime());
            return new Message(Code.SUCCESS, js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_addFamily】业主授权家人异常",e);
        }
    }


    /**
     * <desc>
     *      业主移除家人
     * <desc/>
     * @param   appid   应用接入凭证
     * @param   userPhone   业主手机号
     * @param   authPhoneNo   家人手机号
     * @param   projectId   项目编号
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/22
     */
    @ResponseBody
    @RequestMapping("/app/authPerson/delete")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_DELETE_FAMILY_LOG_DESC)
    public Message appDelete(String appid, String userPhone, String authPhoneNo, String projectId) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }

            if(StringUtils.isEmpty(userPhone) || !userPhone.matches(PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "userPhone为空或格式不正确：" + userPhone);
            }

            if(StringUtils.isEmpty(authPhoneNo) || !authPhoneNo.matches(PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "authPhoneNo为空或格式不正确：" + authPhoneNo);
            }

            Map<String,Object> param = new HashMap<>();
            param.put("parentPhone",userPhone);
            param.put("authPhone",authPhoneNo);
            param.put("projectId",desProjectId);
            List<AppAuthRelationsPO> authRelationsPOS = iSDKUserServiceClient.getAuthRelationsByParams(param);
            if(authRelationsPOS == null || authRelationsPOS.isEmpty()){
                return  new Message(Code.NOT_FOUNDUSER,"该授权人没有授权该住户");
            }

            Message returnMessqge = iAppOldMineServiceClient.delUserChild(userPhone,authPhoneNo,desProjectId);
            String r = returnMessqge.getMsgCode();

            if ("0".equals(r)) {
                JSONObject projectJS = isdkAppOldUserServiceClient.getUserProjectInfo(authRelationsPOS.get(0).getUserId(),"");
                JSONObject js = new JSONObject();
                String projectIds = projectJS.getString("projectIds");
                Set<String> projectIdSet = new HashSet<>();
                if(StringUtils.isNotEmpty(projectIds)){
                    String[] projectIdArr = projectIds.split(",");
                    for (String pId : projectIdArr) {
                        projectIdSet.add(DesEncryptUtil.projectIdEncrypt(pId,"",""));
                    }
                }
                js.put("projectIds", String.join(",",projectIdSet));
                js.put("projectNames", projectJS.getString("projectNames"));
                js.put("userTypeInProject", projectJS.getString("userTypeInProject"));
                js.put("userAuth", projectJS.getString("userAuth"));
                js.put("pubKeys", projectJS.getString("pubKeys"));
                js.put("userSortNum", String.valueOf(RandomUtil.getRandomAround(8,1)));
                return new Message(Code.SUCCESS,js);
        }
        return returnMessqge;
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_appDelete】业主移除家人异常",e);
        }
    }

    /**
     * <desc>
     *      获取被授权人列表
     * <desc/>
     * @param   appid   应用接入凭证
     * @param   sdkAuthUserGetPageDTO   分页查询条件对象
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/22
     */
    @ResponseBody
    @RequestMapping("/app/authPerson/list")
    public Message myAuthPersionList(String appid, SDKAuthUserGetPageDTO sdkAuthUserGetPageDTO) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(sdkAuthUserGetPageDTO.getProjectId());
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }
            String userPhone = sdkAuthUserGetPageDTO.getUserPhone();
            if (StringUtils.isEmpty(userPhone) || !userPhone.matches(PlatformConstants.USER_PHONENUM_REGIX)) {
                return new Message(Code.PARAM_ERR, "userPhone为空或格式不正确");
            }


            Map<String, Object> param = new HashMap<>();
            param.put("parentPhone", userPhone);
            param.put("projectId", desProjectId);
            List<AppAuthRelationsPO> authRelationsPOS = iSDKUserServiceClient.getAuthRelationsByParams(param);

            if (authRelationsPOS == null || authRelationsPOS.isEmpty()) {
                return new Message(Code.NOT_FOUNDUSER, "该授权人没有授权人列表");
            }

            //AppUserInfoPO appUserInfoPO = iSDKUserServiceClient.getAppUserByPhone(userPhone);
            sdkAuthUserGetPageDTO.setProjectId(desProjectId);
            Page<AppAuthRelationsPO> page = iSDKUserServiceClient.getAuthRelationsPage(sdkAuthUserGetPageDTO);

            List<SDKAuthRelationsGetPageVO> dtos = new ArrayList<>();
            authRelationsPOS = page.getRows();
            if (authRelationsPOS != null && !authRelationsPOS.isEmpty()) {
                for (AppAuthRelationsPO authRelations : authRelationsPOS) {
                    //遍历查询被授权用户的基本信息
                    AppUserInfoPO userInfoPO = iSDKUserServiceClient.getAppUserByUserId(authRelations.getUserId());
                    if (userInfoPO != null) {
                        String icon = userInfoPO.getIcon();
                        SDKAuthRelationsGetPageVO sdkAuthRelationsGetPageVO = new SDKAuthRelationsGetPageVO(userInfoPO.getPhoneNum(),
                                userInfoPO.getRealName(), authRelations.getUserRemarks(), StringUtils.isEmpty(icon)?"":icon, authRelations.getCreateTime().toString());
                        dtos.add(sdkAuthRelationsGetPageVO);
                    }
                }
            }
            return new Message(Code.SUCCESS, "", dtos);
            /*Integer pageNo = sdkAuthUserGetPageDTO.getPageNo();
            Integer pageSize = sdkAuthUserGetPageDTO.getPageSize();
            pageNo = (pageNo==null)?1:pageNo;
            pageSize = (pageSize==null)?1:pageSize;
            return iAppOldMineServiceClient.getAuthPersionList(desProjectId,appUserInfoPO.getUserId(), pageNo, pageSize);*/

        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_myAuthPersionList】获取被授权人列表异常", e);
        }
    }


    /**
     * <desc>
     *      修改被授权人备注
     * <desc/>
     * @param   appid   应用接入凭证
     * @param   projectId   项目编号
     * @param   userPhone   业主手机号
     * @param   authPhoneNo   家人手机号
     * @param   userRemarks   被授权人备注
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/23
     */
    @ResponseBody
    @RequestMapping("/app/authPerson/update")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_UPDATE_USERREMARKS_LOG_DESC)
    public Message appUpdate(String appid, String projectId,String userPhone, String authPhoneNo, String userRemarks) {
        try {
            //旧的接口中由于没有传projectId，此处独立开发者校验需要注掉
        /*String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
        if (desProjectId == null  ) {
            return new Message(Code.APP_DEVELOP_ERR);
        }
        //校验开发者账号是否有该项目的权限
        Message message = checkServerSDKofProject(appid, desProjectId);
        if (message != null) {
            return message;
        }*/

            if(StringUtils.isEmpty(userPhone) || !userPhone.matches(PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "userPhone为空或格式不正确：" + userPhone);
            }

            if(StringUtils.isEmpty(authPhoneNo) || !authPhoneNo.matches(PlatformConstants.USER_PHONENUM_REGIX)){
                return new Message(Code.PARAM_ERR, "authPhoneNo为空或格式不正确：" + authPhoneNo);
            }

            Map<String,Object> param = new HashMap<>();
            param.put("parentPhone",userPhone);
            param.put("authPhone",authPhoneNo);
            List<AppAuthRelationsPO> authRelationsPOS = iSDKUserServiceClient.getAuthRelationsByParams(param);
            if(authRelationsPOS == null || authRelationsPOS.isEmpty()){
                return  new Message(Code.NOT_FOUNDUSER,"该授权人没有授权该住户");
            }

            AppAuthRelationsPO authRelationsPO = authRelationsPOS.get(0);
            authRelationsPO.setUserRemarks(userRemarks);
            authRelationsPO.setUpdateTime(new Date());

            iSDKUserServiceClient.updateAuthRelations(authRelationsPO);
            return new Message(Code.SUCCESS);
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_appUpdate】修改被授权人备注异常",e);
        }
    }

    /**
     * <desc>
     *      批量往存在的房间中添加住户：如果该房间中不存在业主，则添加为业主，否则添加为家属
     * <desc/>
     * @param   appid   应用接入凭证
     * @param   projectId   项目编号
     * @param   userJson   添加住户的数据信息：包含手机号和房间信息
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/23
     */
    @ResponseBody
    @RequestMapping("/app/user/add")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_ADD_APPUSER_LOG_DESC)
    public Message sdkAddUser(String appid, String projectId, String userJson) {
        try {
            String desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId);
            if (desProjectId == null  ) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //校验开发者账号是否有该项目的权限
            Message message = checkServerSDKofProject(appid, desProjectId);
            if (message != null) {
                return message;
            }

            JSONArray errarray = new JSONArray();
            List<SDKAppUserSaveDTO> userSdkDtos = new ArrayList<>();

            try {
                if (StringUtils.isNotEmpty(userJson)) {
                    JSONObject uj = JSONObject.parseObject(userJson);
                    String userArr = uj.getString("userArr");
                    userSdkDtos = JSONObject.parseObject(userArr, new TypeReference<List<SDKAppUserSaveDTO>>() {
                    });
                } else {
                    return new Message(Code.NOT_PARAM, "userJson不能为空" + userJson);
                }
            } catch (Exception e) {
                return new Message(Code.PARAM_ERR, "请检查userJson格式");
            }
            if (userSdkDtos == null || userSdkDtos.isEmpty()) {
                return new Message(Code.NOT_PARAM, "请至少添加一个用户");
            }
            List<SDKSaveAppUserDTO> saveAppUserDTOs = new ArrayList<>();
            for (SDKAppUserSaveDTO userSdkDto : userSdkDtos) {
                String phoneNo = userSdkDto.getPhoneNo();
                if (StringUtils.isEmpty(phoneNo) || !phoneNo.matches(PlatformConstants.USER_PHONENUM_REGIX)) {
                    errarray.add(JSONObject.toJSON(String.format("%s：%s", "用户手机号格式不正确：", phoneNo)));
                    continue;
                }
                List<SDKRoomInfoSaveDTO> roomDTOs = userSdkDto.getRoomArr();
                List<SDKRoomInfoSaveDTO> saveRoomDTOs = new ArrayList<>();
                if (null != roomDTOs && roomDTOs.size() > 0) {
                    //验证房间是否存在
                    for (SDKRoomInfoSaveDTO roomDTO : roomDTOs) {
                        String buildNum = roomDTO.getBuildNum();
                        String unitNum = roomDTO.getUnitNum();
                        String roomNum = roomDTO.getRoomNum();
                        Map<String, Object> paramMap = new HashMap<>();
                        paramMap.put("projectId", desProjectId);
                        paramMap.put("buildNum", buildNum);
                        paramMap.put("unitNum", unitNum);
                        paramMap.put("roomNum", roomNum);
                        List<RoomInfoPO> existRooms = iSDKServerRoomClient.getRoomByPiBnUnRn(paramMap);
                        if (existRooms == null || existRooms.isEmpty()) {
                            errarray.add(JSONObject.toJSON("请检查地址是否存在：buildNum:" + buildNum + " unitNum:" + unitNum + " roomNum:" + roomNum));
                            continue;
                        }
                        SDKRoomInfoSaveDTO sdkRoomInfoSaveDTO = new SDKRoomInfoSaveDTO();
                        BeanUtils.copyProperties(existRooms.get(0),sdkRoomInfoSaveDTO);
                        saveRoomDTOs.add(sdkRoomInfoSaveDTO);
                    }
                }
                SDKSaveAppUserDTO sdkSaveAppUserDTO = new SDKSaveAppUserDTO(desProjectId, appid, phoneNo, null, saveRoomDTOs, null);
                saveAppUserDTOs.add(sdkSaveAppUserDTO);
            }

            if (!errarray.isEmpty()) {
                return new Message(Code.ERROR, "用户信息错误/缺少必要参数  reqParams:" + errarray.toJSONString());
            } else {
                if (saveAppUserDTOs == null || saveAppUserDTOs.isEmpty()) {
                    return new Message(Code.NOT_PARAM, "请至少添加一个用户");
                }
                Map<String, Object> countMap = iSDKUserServiceClient.addAppUsers(saveAppUserDTOs);
                Integer existUser = (Integer) countMap.get("existUser");
                Integer addUserCount = (Integer) countMap.get("addUserCount");
                return new Message(Code.SUCCESS, String.format("%s%s%s%s", "本次共添加：", addUserCount, "个用户", (existUser > 0 ? "," + existUser + "个用户已经存在" : "")));
            }
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKServerOldUserController_appUpdate】批量添加住户异常",e);
        }
    }


    /**
     * <desc>
     *      校验开发者账号是否有该项目的权限
     * <desc/>
     * @param   appid     应用接入凭证
     * @param    projectId     独立开发者所管辖的项目Id
     * @return  Message   老版标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/6
     */
    private Message checkServerSDKofProject(String appid, String projectId) {
        PropertyRoleProjectPO roleProjectPO = new PropertyRoleProjectPO(projectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(), appid);
        List<PropertyRoleProjectPO> roleProjectPOS = iSDKUserServiceClient.getRoleProject(roleProjectPO);
        if (roleProjectPOS != null && roleProjectPOS.isEmpty()) {
            return new Message(Code.NOT_PERMISSION);
        }
        return null;
    }
}